import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import './AdminAppointmentManagementPage.css';
import * as appointmentService from '../services/appointmentService';

const AdminAppointmentManagementPage = () => {
  const navigate = useNavigate();
  const [appointments, setAppointments] = useState([]);
  const [filteredAppointments, setFilteredAppointments] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  
  // 筛选条件状态
  const [filters, setFilters] = useState({
    patientName: '',
    doctorName: '',
    departmentName: '',
    status: '',
    startDate: '',
    endDate: '',
  });
  
  // 分页状态
  const [currentPage, setCurrentPage] = useState(1);
  const [appointmentsPerPage] = useState(10);
  
  // 模态框状态
  const [showModal, setShowModal] = useState(false);
  const [modalType, setModalType] = useState(''); // 'create', 'edit', 'view'
  const [currentAppointment, setCurrentAppointment] = useState(null);
  
  // 加载所有预约
  useEffect(() => {
    const fetchAppointments = async () => {
      try {
        console.log("开始获取预约列表...");
        setLoading(true);
        
        // 检查用户认证信息
        const token = localStorage.getItem('token');
        if (!token) {
          console.error("未找到认证Token");
          setError('用户未登录或认证已过期，请重新登录');
          setLoading(false);
          return;
        }
        
        console.log("调用appointmentService.getAllAppointments...");
        const data = await appointmentService.getAllAppointments();
        console.log("获取预约列表成功:", data);
        
        if (Array.isArray(data)) {
          setAppointments(data);
          setFilteredAppointments(data);
        } else {
          console.error("API返回的数据不是数组:", data);
          setError('获取预约列表失败：返回数据格式错误');
        }
        
        setLoading(false);
      } catch (err) {
        console.error("获取预约列表失败:", err);
        
        // 处理认证失败错误
        if (err.response && err.response.status === 403) {
          setError('没有权限访问预约列表，请确认您是否有管理员权限');
          
          // 如果没有管理员权限，可以重定向到登录页
          // setTimeout(() => navigate('/login'), 2000);
        } else if (err.response && err.response.status === 401) {
          setError('您的登录已过期，请重新登录');
          
          // 认证过期，重定向到登录页
          // setTimeout(() => navigate('/login'), 2000);
        } else {
          setError('获取预约列表失败：' + (err.response?.data?.message || err.message || '未知错误'));
        }
        
        setLoading(false);
      }
    };
    
    fetchAppointments();
  }, [navigate]);
  
  // 处理筛选操作
  useEffect(() => {
    let results = [...appointments];
    
    if (filters.patientName) {
      results = results.filter(appointment => 
        appointment.patientName.toLowerCase().includes(filters.patientName.toLowerCase())
      );
    }
    
    if (filters.doctorName) {
      results = results.filter(appointment => 
        appointment.doctorName.toLowerCase().includes(filters.doctorName.toLowerCase())
      );
    }
    
    if (filters.departmentName) {
      results = results.filter(appointment => 
        appointment.departmentName.toLowerCase().includes(filters.departmentName.toLowerCase())
      );
    }
    
    if (filters.status) {
      results = results.filter(appointment => appointment.status === filters.status);
    }
    
    if (filters.startDate && filters.endDate) {
      results = results.filter(appointment => {
        const appointmentDate = new Date(appointment.appointmentDate);
        const start = new Date(filters.startDate);
        const end = new Date(filters.endDate);
        return appointmentDate >= start && appointmentDate <= end;
      });
    }
    
    setFilteredAppointments(results);
    setCurrentPage(1);
  }, [filters, appointments]);
  
  // 获取当前页的预约
  const indexOfLastAppointment = currentPage * appointmentsPerPage;
  const indexOfFirstAppointment = indexOfLastAppointment - appointmentsPerPage;
  const currentAppointments = filteredAppointments.slice(indexOfFirstAppointment, indexOfLastAppointment);
  
  // 处理分页
  const paginate = (pageNumber) => setCurrentPage(pageNumber);
  
  // 处理筛选条件变化
  const handleFilterChange = (e) => {
    const { name, value } = e.target;
    setFilters(prevFilters => ({
      ...prevFilters,
      [name]: value
    }));
  };
  
  // 重置筛选条件
  const resetFilters = () => {
    setFilters({
      patientName: '',
      doctorName: '',
      departmentName: '',
      status: '',
      startDate: '',
      endDate: '',
    });
  };
  
  // 手动重新加载数据
  const handleReload = async () => {
    setError(null);
    setLoading(true);
    try {
      const data = await appointmentService.getAllAppointments();
      setAppointments(data);
      setFilteredAppointments(data);
      setLoading(false);
    } catch (err) {
      console.error("重新加载预约列表失败:", err);
      setError('重新加载预约列表失败');
      setLoading(false);
    }
  };
  
  // 打开创建预约模态框
  const openCreateModal = () => {
    setCurrentAppointment({
      patientId: '',
      doctorId: '',
      departmentId: '',
      appointmentDate: '',
      appointmentTime: '',
      reason: '',
      status: 'PENDING',
      notes: ''
    });
    setModalType('create');
    setShowModal(true);
  };
  
  // 打开编辑预约模态框
  const openEditModal = (appointment) => {
    setCurrentAppointment({
      id: appointment.id,
      patientId: appointment.patientId,
      doctorId: appointment.doctorId,
      departmentId: appointment.departmentId,
      appointmentDate: appointment.appointmentDate,
      appointmentTime: appointment.appointmentTime,
      reason: appointment.reason,
      status: appointment.status,
      notes: appointment.notes
    });
    setModalType('edit');
    setShowModal(true);
  };
  
  // 打开查看预约详情模态框
  const openViewModal = (appointment) => {
    setCurrentAppointment(appointment);
    setModalType('view');
    setShowModal(true);
  };
  
  // 关闭模态框
  const closeModal = () => {
    setShowModal(false);
    setCurrentAppointment(null);
  };
  
  // 处理表单输入变化
  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setCurrentAppointment(prev => ({
      ...prev,
      [name]: value
    }));
  };
  
  // 提交预约表单
  const handleSubmit = async (e) => {
    e.preventDefault();
    
    try {
      if (modalType === 'create') {
        await appointmentService.createAppointment(currentAppointment);
      } else if (modalType === 'edit') {
        await appointmentService.updateAppointment(currentAppointment.id, currentAppointment);
      }
      
      // 重新加载预约列表
      const updatedAppointments = await appointmentService.getAllAppointments();
      setAppointments(updatedAppointments);
      closeModal();
    } catch (err) {
      setError('处理预约失败');
    }
  };
  
  // 处理预约状态变更
  const handleStatusChange = async (appointmentId, newStatus) => {
    try {
      await appointmentService.updateAppointmentStatus(appointmentId, newStatus);
      // 重新加载预约列表
      const updatedAppointments = await appointmentService.getAllAppointments();
      setAppointments(updatedAppointments);
    } catch (err) {
      setError('更新预约状态失败');
    }
  };
  
  // 处理删除预约
  const handleDeleteAppointment = async (appointmentId) => {
    if (window.confirm('确定要删除这个预约吗？')) {
      try {
        await appointmentService.deleteAppointment(appointmentId);
        // 重新加载预约列表
        const updatedAppointments = await appointmentService.getAllAppointments();
        setAppointments(updatedAppointments);
      } catch (err) {
        setError('删除预约失败');
      }
    }
  };
  
  // 渲染状态标签样式
  const renderStatusBadge = (status) => {
    const statusMap = {
      'PENDING': { className: 'status-pending', label: '待确认' },
      'CONFIRMED': { className: 'status-confirmed', label: '已确认' },
      'CANCELED': { className: 'status-canceled', label: '已取消' },
      'COMPLETED': { className: 'status-completed', label: '已完成' }
    };
    
    const statusInfo = statusMap[status] || { className: '', label: status };
    
    return (
      <span className={`status-badge ${statusInfo.className}`}>
        {statusInfo.label}
      </span>
    );
  };
  
  return (
    <div className="appointment-management-container">
      <div className="appointment-management-header">
        <h2>预约管理</h2>
        <div>
          <button className="btn btn-secondary" onClick={handleReload} style={{ marginRight: '10px' }}>
            刷新数据
          </button>
          <button className="btn btn-primary" onClick={openCreateModal}>
            新建预约
          </button>
        </div>
      </div>
      
      {error && (
        <div className="error-message" style={{ 
          backgroundColor: '#ffebee', 
          color: '#c62828', 
          padding: '10px', 
          borderRadius: '4px', 
          marginBottom: '15px',
          display: 'flex',
          justifyContent: 'space-between'
        }}>
          <span>{error}</span>
          <button 
            onClick={() => setError(null)} 
            style={{ 
              background: 'none', 
              border: 'none', 
              cursor: 'pointer',
              fontWeight: 'bold',
              color: '#c62828'
            }}
          >
            ✕
          </button>
        </div>
      )}
      
      <div className="filter-bar">
        <div className="filter-row">
          <div className="filter-item">
            <label className="filter-label">患者姓名</label>
            <input
              type="text"
              name="patientName"
              value={filters.patientName}
              onChange={handleFilterChange}
              className="filter-input"
              placeholder="搜索患者姓名"
            />
          </div>
          <div className="filter-item">
            <label className="filter-label">医生姓名</label>
            <input
              type="text"
              name="doctorName"
              value={filters.doctorName}
              onChange={handleFilterChange}
              className="filter-input"
              placeholder="搜索医生姓名"
            />
          </div>
          <div className="filter-item">
            <label className="filter-label">科室名称</label>
            <input
              type="text"
              name="departmentName"
              value={filters.departmentName}
              onChange={handleFilterChange}
              className="filter-input"
              placeholder="搜索科室名称"
            />
          </div>
        </div>
        
        <div className="filter-row">
          <div className="filter-item">
            <label className="filter-label">预约状态</label>
            <select
              name="status"
              value={filters.status}
              onChange={handleFilterChange}
              className="filter-select"
            >
              <option value="">所有状态</option>
              <option value="PENDING">待确认</option>
              <option value="CONFIRMED">已确认</option>
              <option value="CANCELED">已取消</option>
              <option value="COMPLETED">已完成</option>
            </select>
          </div>
          <div className="filter-item">
            <label className="filter-label">开始日期</label>
            <input
              type="date"
              name="startDate"
              value={filters.startDate}
              onChange={handleFilterChange}
              className="filter-input"
            />
          </div>
          <div className="filter-item">
            <label className="filter-label">结束日期</label>
            <input
              type="date"
              name="endDate"
              value={filters.endDate}
              onChange={handleFilterChange}
              className="filter-input"
            />
          </div>
        </div>
        
        <div className="filter-buttons">
          <button className="btn btn-secondary" onClick={resetFilters}>重置筛选</button>
        </div>
      </div>
      
      {loading ? (
        <p>加载中...</p>
      ) : (
        <>
          <table className="appointment-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>患者姓名</th>
                <th>医生姓名</th>
                <th>科室名称</th>
                <th>预约日期</th>
                <th>预约时间</th>
                <th>状态</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              {currentAppointments.length > 0 ? (
                currentAppointments.map(appointment => (
                  <tr key={appointment.id}>
                    <td>{appointment.id}</td>
                    <td>{appointment.patientName}</td>
                    <td>{appointment.doctorName}</td>
                    <td>{appointment.departmentName}</td>
                    <td>{appointment.appointmentDate}</td>
                    <td>{appointment.appointmentTime}</td>
                    <td>{renderStatusBadge(appointment.status)}</td>
                    <td>
                      <div className="action-buttons">
                        <button 
                          className="btn btn-primary" 
                          onClick={() => openViewModal(appointment)}
                        >
                          查看
                        </button>
                        <button 
                          className="btn btn-warning" 
                          onClick={() => openEditModal(appointment)}
                        >
                          编辑
                        </button>
                        <button 
                          className="btn btn-danger" 
                          onClick={() => handleDeleteAppointment(appointment.id)}
                        >
                          删除
                        </button>
                        {appointment.status === 'PENDING' && (
                          <button 
                            className="btn btn-success" 
                            onClick={() => handleStatusChange(appointment.id, 'CONFIRMED')}
                          >
                            确认
                          </button>
                        )}
                        {appointment.status === 'CONFIRMED' && (
                          <button 
                            className="btn btn-secondary" 
                            onClick={() => handleStatusChange(appointment.id, 'COMPLETED')}
                          >
                            完成
                          </button>
                        )}
                        {(appointment.status === 'PENDING' || appointment.status === 'CONFIRMED') && (
                          <button 
                            className="btn btn-danger" 
                            onClick={() => handleStatusChange(appointment.id, 'CANCELED')}
                          >
                            取消
                          </button>
                        )}
                      </div>
                    </td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan="8" style={{ textAlign: 'center' }}>没有找到符合条件的预约</td>
                </tr>
              )}
            </tbody>
          </table>
          
          {/* 分页控件 */}
          {filteredAppointments.length > 0 && (
            <div className="pagination">
              {Array.from({ length: Math.ceil(filteredAppointments.length / appointmentsPerPage) }, (_, i) => (
                <button
                  key={i + 1}
                  onClick={() => paginate(i + 1)}
                  className={`pagination-button ${currentPage === i + 1 ? 'active' : ''}`}
                >
                  {i + 1}
                </button>
              ))}
            </div>
          )}
        </>
      )}
      
      {/* 预约模态框 */}
      {showModal && (
        <div className="modal-overlay">
          <div className="modal-content">
            <div className="modal-header">
              <h3>
                {modalType === 'create' ? '新建预约' : modalType === 'edit' ? '编辑预约' : '预约详情'}
              </h3>
              <button className="modal-close" onClick={closeModal}>&times;</button>
            </div>
            
            {modalType === 'view' ? (
              <div className="appointment-details">
                <p><strong>患者:</strong> {currentAppointment.patientName}</p>
                <p><strong>医生:</strong> {currentAppointment.doctorName}</p>
                <p><strong>科室:</strong> {currentAppointment.departmentName}</p>
                <p><strong>日期:</strong> {currentAppointment.appointmentDate}</p>
                <p><strong>时间:</strong> {currentAppointment.appointmentTime}</p>
                <p><strong>原因:</strong> {currentAppointment.reason}</p>
                <p><strong>状态:</strong> {renderStatusBadge(currentAppointment.status)}</p>
                <p><strong>备注:</strong> {currentAppointment.notes}</p>
                <p><strong>创建时间:</strong> {new Date(currentAppointment.createdAt).toLocaleString()}</p>
                <p><strong>更新时间:</strong> {new Date(currentAppointment.updatedAt).toLocaleString()}</p>
                
                <div className="form-actions">
                  <button className="btn btn-primary" onClick={closeModal}>关闭</button>
                </div>
              </div>
            ) : (
              <form onSubmit={handleSubmit}>
                <div className="form-group">
                  <label className="form-label">患者ID</label>
                  <input
                    type="text"
                    name="patientId"
                    value={currentAppointment.patientId}
                    onChange={handleInputChange}
                    className="form-input"
                    required
                  />
                </div>
                
                <div className="form-group">
                  <label className="form-label">医生ID</label>
                  <input
                    type="text"
                    name="doctorId"
                    value={currentAppointment.doctorId}
                    onChange={handleInputChange}
                    className="form-input"
                    required
                  />
                </div>
                
                <div className="form-group">
                  <label className="form-label">科室ID</label>
                  <input
                    type="text"
                    name="departmentId"
                    value={currentAppointment.departmentId}
                    onChange={handleInputChange}
                    className="form-input"
                    required
                  />
                </div>
                
                <div className="form-group">
                  <label className="form-label">预约日期</label>
                  <input
                    type="date"
                    name="appointmentDate"
                    value={currentAppointment.appointmentDate}
                    onChange={handleInputChange}
                    className="form-input"
                    required
                  />
                </div>
                
                <div className="form-group">
                  <label className="form-label">预约时间</label>
                  <input
                    type="time"
                    name="appointmentTime"
                    value={currentAppointment.appointmentTime}
                    onChange={handleInputChange}
                    className="form-input"
                    required
                  />
                </div>
                
                <div className="form-group">
                  <label className="form-label">预约原因</label>
                  <textarea
                    name="reason"
                    value={currentAppointment.reason}
                    onChange={handleInputChange}
                    className="form-textarea"
                    required
                  />
                </div>
                
                <div className="form-group">
                  <label className="form-label">状态</label>
                  <select
                    name="status"
                    value={currentAppointment.status}
                    onChange={handleInputChange}
                    className="form-select"
                    required
                  >
                    <option value="PENDING">待确认</option>
                    <option value="CONFIRMED">已确认</option>
                    <option value="CANCELED">已取消</option>
                    <option value="COMPLETED">已完成</option>
                  </select>
                </div>
                
                <div className="form-group">
                  <label className="form-label">备注</label>
                  <textarea
                    name="notes"
                    value={currentAppointment.notes}
                    onChange={handleInputChange}
                    className="form-textarea"
                  />
                </div>
                
                <div className="form-actions">
                  <button type="button" className="btn btn-secondary" onClick={closeModal}>取消</button>
                  <button type="submit" className="btn btn-primary">
                    {modalType === 'create' ? '创建' : '保存'}
                  </button>
                </div>
              </form>
            )}
          </div>
        </div>
      )}
    </div>
  );
};

export default AdminAppointmentManagementPage; 